package com.common.web.util;


import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.common.api.exception.CommonException;
import com.common.util.DateParseUtil;
 
/**
 * 支持多种时间格式转换
 */
public class DateFormatPlugin extends SimpleDateFormat {
 
	private static final long serialVersionUID = 1L;
	
	private static ThreadLocal<DateFormat> safeSdf = new ThreadLocal<DateFormat>(){
        @Override 
        protected SimpleDateFormat initialValue(){
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };
    
	@Override
	public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
		return safeSdf.get().format(date, toAppendTo, pos);
	}
 
    @Override
    public Date parse(String source) {
        String value = source.trim();
        if ("".equals(value)) {
            return null;
        }
     	try {
     		Date result=DateParseUtil.parseDate(value);
    		return result; 				
		} catch (Exception e) {
			throw new CommonException("时间参数:"+value+",解析失败!");
		}        
    }
}
 